//#########################################################################
//                              WackiEngie
//           Copyright (c) 2014 Marc Wacker. All rights reserved.
//#########################################################################

#include "WeImage.h"

// we use the stb image header to load image files at the moment
// not all formats work but its light weight and easy to use
#include "stb_image.h"

namespace WackiEngine
{

	Image::Image()
	{
		_data = NULL;
	}

	Image::Image(const String& fileName)
	{
		load(fileName);
	}

	Image::~Image()
	{
		clear();
	}


	void Image::clear()
	{
		if(_data)
			delete[] _data;
	}

	void* Image::load(const String& fileName)
	{
		//clear previous data
		clear();

		void *result = 0;
		int cmp;
		
		// if hdr data load as float:
		if(stbi_is_hdr(fileName.c_str())) {
			result = stbi_loadf(fileName.c_str(), &_width, &_height, &cmp, 0);

			if(!result)
				goto FAILURE;
			switch(cmp) {
			case 1: _format = GL_R16F;		_srcDataFormat = GL_RED;	break;
			case 2: _format = GL_RG16F;		_srcDataFormat = GL_RG;		break;
			case 3: _format = GL_RGB16F;	_srcDataFormat = GL_RGB;	break;
			case 4: _format = GL_RGBA16F;	_srcDataFormat = GL_RGBA;	break;
			}
			_srcDataType = GL_FLOAT;
			_pixelSize = cmp * sizeof(float);
		}
		else {
			result = stbi_load(fileName.c_str(), &_width, &_height, &cmp, 0);
			if(!result)
				goto FAILURE;
			switch(cmp) {
			case 1: _srcDataFormat = _format = GL_RED;	break;
			case 2: _srcDataFormat = _format = GL_RG;	break;
			case 3: _srcDataFormat = _format = GL_RGB;	break;
			case 4: _srcDataFormat = _format = GL_RGBA;	break;
			}
			_srcDataType = GL_UNSIGNED_BYTE;
			_pixelSize = cmp * sizeof(uchar);
		}

		_data = result;
		/*/
		for(int y = 0; y < height(); ++y) {
			for(int x = 0; x < width(); ++x) {
				int index = (x*3) + y * (width()*3);
				std::cout << "(" << (int)((uchar*)(_data))[index] << ", " << (int)((uchar*)(_data))[index + 1] << ", " << (int)((uchar*)(_data))[index + 2] << ") ";
			}

			std::cout << std::endl;
		}
		*/
		return result;

	FAILURE:
		return NULL;
	}

}